package com.mutouren.web;

import java.util.Map;

import org.springframework.context.ApplicationContext;

import com.mutouren.common.entity.ValidState;
import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.mutouren.common.utils.PropertiesUtils;
import com.mutouren.common.utils.StringUtils;
import com.mutouren.modules.org.model.App;
import com.mutouren.modules.org.service.AppService;

public class SystemConfig {
	private static Logger runLogger = LogManager.getLogger(LogAlias.SystemRun.name());
	private static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());
	
	private final static String path = "/mtr.properties";
	private static String appAlias;
	private volatile static App app = null;
	
	public static App getApp() {
		return app;
	}
	public static String getAppAlias() {
		return appAlias;
	}
	
	static {
		try {
			runLogger.info("mutouren load SystemConfig start");
			Map<String, String> map = PropertiesUtils.getConfig(path);
			appAlias = map.get("appAlias");
			if (StringUtils.isBlank(appAlias)) {
				throw new RuntimeException("SystemConfig not find appAlias");
			}
			runLogger.info("mutouren load SystemConfig finish");
		} catch (Throwable t){
			errorLogger.error("mutouren load SystemConfig error", t);
			throw t;
		}
	}
	
	public static void init(ApplicationContext context) {
		AppService appService = context.getBean(AppService.class);
		app = appService.getByAppAlias(appAlias);
		if (app == null) {
			throw new RuntimeException(String.format("AppManager.init fail: not find appAlias %s", appAlias));
		}
		
		if (app.getValidState() != ValidState.Normal) {
			throw new RuntimeException(String.format("AppManager.init fail: appAlias %s validState isn't normal", appAlias));
		}
	}
	
	public static void main(String[] args) {
		System.out.println(getAppAlias());
	}	
}
